#! /bin/bash

## scan ip mac

IPMAC_FILE=~huan/mydoc/ipmac
DEFAULT_LAN="192.168.1.0/24"
BLACK_IP="192.168.1.1"

LAN="$1"
[[ -z "$LAN" ]] && LAN="$DEFAULT_LAN"

if (( UID != 0 )); then
    echo "root privilege to get mac"
    exit 1
fi

## just scan ...
scan_lan()
{
    nmap -n -sP "$LAN"
}

## get ip mac
get_ipmac()
{
    awk '{
        if ( $1 ~ /^Host/ ) {
            ip = $2;
        }
        else if ( $1 ~ /^MAC/ ) {
            mac = $3;
            print ip, mac;
        }
    }'
}

## check if the ip in blacklist
is_inblack()
{
    local ip=$1
    for black_ip in $BLACK_IP; do
        [[ "$black_ip" == "$ip" ]] && return 0
    done        

    return 1
}

## check if the ip in db file
is_indb()
{
    local ipmac="$1 $2"
    grep -xq "$ipmac" "$IPMAC_FILE"

    return $?
}

## update db file
update_db()
{
    local ip
    local mac
    while read ip mac; do
        if is_inblack "$ip" || is_indb "$ip" "$mac"; then
            :
        else
            echo "$ip $mac" | tee -a "$IPMAC_FILE"
        fi
    done
}

#-------------------- main --------------------

scan_lan  |
get_ipmac |
update_db
